
#ifndef G1_HEAP_HPP
#define G1_HEAP_HPP

#include "g1_region.hpp"
#include <queue>
#include <vector>
#include <set>
#include <memory>
class G1Heap
{
private:
    static const size_t HEAP_SIZE = 1024 * 1024 * 1024; // 1GB 的堆大小
    static const size_t REGION_COUNT = HEAP_SIZE / G1Region::get_region_size();
    G1Region *regions[REGION_COUNT];
    void *heap_start;
    int current_gc_epoch;

    // 根对象集合
    struct RootSet
    {
        std::vector<void *> static_roots;
        std::vector<void *> stack_roots;
        std::vector<void *> jni_roots;

        void add_root(void *root)
        {
            static_roots.push_back(root);
        }
    } roots;

    // 标记队列
    class MarkQueue
    {
    private:
        std::queue<void *> queue;
        std::set<void *> marked_objects;

    public:
        void push(void *obj)
        {
            if (marked_objects.insert(obj).second)
            {
                queue.push(obj);
            }
        }

        void* pop()
        {
            if (!queue.empty())
            {
                void *obj = queue.front();
                queue.pop();
                return obj;
            }
            return nullptr;
        }

        bool empty() const { return queue.empty(); }
    } mark_queue;

public:
    G1Heap();
    ~G1Heap();

    void* allocate(size_t size);
    void collect_garbage();
    void add_root(void *root){
        roots.add_root(root);
    };
private:
    void mark_roots();
    void process_mark_queue();
    std::vector<void*> get_object_references(G1Object* obj);
    bool is_valid_heap_pointer(void* p);
    void compact_live_objects();
};
#endif